package com.piece.module.generator.service;

import com.google.common.collect.Maps;
import com.piece.core.db.context.DynamicDataSourceContextHolder;
import com.piece.core.framework.constant.FrameWorkConstants;
import com.piece.core.framework.enums.StatusType;
import com.piece.core.framework.enums.sql.SqlKey;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.db.util.DataBaseUtil;
import com.piece.core.framework.support.bootstrap.Order;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.module.generator.constants.GenConstants;
import com.piece.module.generator.model.GenTable;
import com.piece.module.generator.model.GenTableColumn;
import com.piece.module.generator.model.TbSysDb;
import com.piece.module.generator.model.TbSysValidate;
import com.piece.module.generator.properties.GenProperties;
import com.piece.module.generator.util.GenUtil;
import com.piece.module.generator.util.VelocityInitializer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成处理
 */
@Slf4j
@Service
public class GenService {

    @Resource
    private GenProperties genProperties;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private GenTableService genTableService;

    @Resource
    private GenTableColumnService genTableColumnService;

    @Resource
    private TbSysValidateService tbSysValidateService;

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    private static String table_mysql = "select t.table_name TABLENAME, t.table_comment TABLECOMMENT " +
            " from information_schema.tables t " +
            " where t.table_comment <> '' and t.table_schema = (select database()) ";

    private static String table_oracle = "select t.table_name TABLENAME,f.comments TABLECOMMENT from user_tables t inner join user_tab_comments f on t.table_name = f.table_name where 1=1 ";

    private static String table_sqlserver = "select cast(t.name as varchar(500)) as TABLENAME, cast(p.[value] as varchar(500)) as TABLECOMMENT " +
            " from sys.tables t left join sys.extended_properties p " +
            " on (t.object_id = p.major_id and p.minor_id = 0) where 1=1 ";

    private static String table_sybase = "select t.name as TABLENAME, '' as TABLECOMMENT from sysobjects t where t.type='U' ";

    private static String column_mysql = "select column_name COLUMNNAME, column_type DATATYPE, column_comment COLUMNCOMMENT, column_key COLUMNKEY, extra EXTRA " +
            " from information_schema.columns " +
            " where table_name ='?table_name' " +
            " and table_schema = (select database()) order by ordinal_position";

    private static String column_oracle = "select col.column_name COLUMNNAME, col.data_type DATATYPE, comm.comments COLUMNCOMMENT, col.column_id COLUMNKEY, '' EXTRA " +
            " from user_tab_columns col inner join user_col_comments comm " +
            " on col.column_name = comm.column_name " +
            " where col.table_name='?table_name' and comm.table_name='?table_name' order by col.column_id";

    private static String column_sqlserver = "select cast(col.name as varchar(500)) as COLUMNNAME, cast(t.name as varchar(500)) as DATATYPE, cast(ep.[value] as varchar(500)) as COLUMNCOMMENT, cast(col.colid as varchar(500)) as COLUMNKEY, '' as EXTRA " +
            " from dbo.syscolumns col " +
            " left  join dbo.systypes t on col.xtype = t.xusertype " +
            " inner join dbo.sysobjects obj on col.id = obj.id " +
            " and obj.xtype = 'U' " +
            " and obj.status >= 0 " +
            " left join dbo.syscomments comm on col.cdefault = comm.id " +
            " left join sys.extended_properties ep on col.id = ep.major_id " +
            " and col.colid = ep.minor_id " +
            " and ep.name = 'MS_Description' " +
            " left join sys.extended_properties epTwo on obj.id = epTwo.major_id " +
            " and epTwo.minor_id = 0 " +
            " and epTwo.name = 'MS_Description' " +
            " where obj.name = 'tech_tree' " +
            " order by col.colorder";

    private static String column_sybase = "select a.name as COLUMNNAME, c.name as DATATYPE, '' as COLUMNCOMMENT, a.colid as COLUMNKEY, '' as EXTRA " +
            " from syscolumns a, sysobjects b, systypes c " +
            " where a.id = b.id and a.usertype = c.usertype and b.name= 'kc_question' " +
            " order by a.colid";

    public void clearGenTable() {
        String sql = "truncate table gen_table";
        jdbcTemplate.execute(sql);
        sql = "truncate table gen_table_column";
        jdbcTemplate.execute(sql);
    }

    public void generateTableColumn(TbSysDb tbSysDb, String tableName) {
        try {

            String[] initSql = getStaticSql(tbSysDb.getDriverClassName(), tbSysDb.getUrl());
            String sql = initSql[0];
            if (StringUtil.isNotEmpty(tableName)) {
                sql += " and t.table_name='" + tableName + "' ";
            }
            List<GenTable> tables = selectTableList(tbSysDb.getDbKey(), sql, null);

            String sql_column = null;
            Map<GenTable, List<GenTableColumn>> tableColumns = new HashMap<>();

            tables = tables.stream().map(genTable -> {
                genTable.setDbKey(tbSysDb.getDbKey());
                supplyGenTable(genTable);
                tableColumns.put(genTable, selectColumnList(tbSysDb.getDbKey(), genTable.getTableName(), initSql[1]));
                return genTable;
            }).collect(Collectors.toList());

            DataBaseUtil.clearDataSource();
            genTableService.batchInsert(tables);

            List<GenTableColumn> columns = new ArrayList<>();
            tableColumns.entrySet().stream().forEach(entry -> {
                GenTable genTable = entry.getKey();
                List<GenTableColumn> columns_ = entry.getValue();
                columns.addAll(columns_.stream().map(genColumn -> {
                    supplyGenColumn(genTable, genColumn);
                    return genColumn;
                }).collect(Collectors.toList()));
            });

            DataBaseUtil.clearDataSource();
            genTableColumnService.batchInsert(columns);
        } catch (Exception e) {
            log.error("初始化业务表数据异常：{}", e.getMessage());
        } finally {
            DataBaseUtil.clearDataSource();
        }
    }

    private void supplyGenTable(GenTable genTable) {
        genTable.setPackageName(genProperties.getPackageName());
        genTable.setModuleName(GenUtil.getModuleName(genProperties.getPackageName()));
        genTable.setBusinessName(GenUtil.getBusinessName(genTable.getTableName()));
        genTable.setFunctionName(GenUtil.replaceKeyword(genTable.getTableComment()));
        genTable.setFunctionAuthor(genProperties.getAuthor());
        genTable.setTplCategory(GenConstants.TPL_CRUD);
    }

    private void supplyGenColumn(GenTable genTable, GenTableColumn genTableColumn) {
        String columnType = genTableColumn.getColumnType();
        String dataType = GenUtil.getDbType(columnType);
        String columnName = genTableColumn.getColumnName();
        genTableColumn.setTableId(genTable.getTableId());
        genTableColumn.setTableName(genTable.getTableName());
        // 设置java字段名
        genTableColumn.setJavaField(StringUtil.convertToCamelCase(columnName));
        if (StringUtil.containsAny(dataType, GenConstants.COLUMNTYPE_STR)) {
            genTableColumn.setJavaType(GenConstants.TYPE_STRING);
            // 字符串长度超过500设置为文本域
            Integer columnLength = GenUtil.getColumnLength(columnType);
            String htmlType = columnLength >= 500 ? GenConstants.HTML_TEXTAREA : GenConstants.HTML_INPUT;
            genTableColumn.setHtmlType(htmlType);
        } else if (StringUtil.containsAny(dataType, GenConstants.COLUMNTYPE_TIME)) {
            genTableColumn.setJavaType(GenConstants.TYPE_DATE);
            genTableColumn.setHtmlType(GenConstants.HTML_DATETIME);
        } else if (StringUtil.containsAny(dataType, GenConstants.COLUMNTYPE_NUMBER)) {
            genTableColumn.setHtmlType(GenConstants.HTML_INPUT);
            String[] str = StringUtil.split(StringUtil.substringBetween(genTableColumn.getColumnType(), "(", ")"), ",");
            if (null != str && str.length == 2 && Integer.parseInt(str[1]) > 0) {
                // 如果是浮点型
                genTableColumn.setJavaType(GenConstants.TYPE_DOUBLE);
            } else if (null != str && str.length == 1 && Integer.parseInt(str[0]) <= 10) {
                // 如果是整形
                genTableColumn.setJavaType(GenConstants.TYPE_INTEGER);
            }  else {
                // 长整形
                genTableColumn.setJavaType(GenConstants.TYPE_LONG);
            }
        } else {
            genTableColumn.setJavaType(GenConstants.TYPE_STRING);
            genTableColumn.setHtmlType(GenConstants.HTML_INPUT);
        }

        // 插入字段（默认所有字段都需要插入）
        genTableColumn.setIsInsert(GenConstants.REQUIRE);

        // 编辑字段
        if (!StringUtil.containsAny(columnName, GenConstants.COLUMNNAME_NOT_EDIT) && !genTableColumn.isPk())  {
            genTableColumn.setIsEdit(GenConstants.REQUIRE);
        }
        // 列表字段
        if (!StringUtil.containsAny(columnName, GenConstants.COLUMNNAME_NOT_LIST) && !genTableColumn.isPk()) {
            genTableColumn.setIsList(GenConstants.REQUIRE);
        }
        // 查询字段
        if (!StringUtil.containsAny(columnName, GenConstants.COLUMNNAME_NOT_QUERY) && !genTableColumn.isPk()) {
            genTableColumn.setIsQuery(GenConstants.REQUIRE);
        }

        // 查询字段类型
        if (StringUtil.endsWithIgnoreCase(columnName, "name")) {
            genTableColumn.setQueryType(GenConstants.QUERY_LIKE);
        }
        // 状态字段设置单选框
        if (StringUtil.endsWithIgnoreCase(columnName, "status")) {
            genTableColumn.setHtmlType(GenConstants.HTML_RADIO);
        } else if (StringUtil.endsWithIgnoreCase(columnName, "type")
                || StringUtil.endsWithIgnoreCase(columnName, "sex")) {
            // 类型&性别字段设置下拉框
            genTableColumn.setHtmlType(GenConstants.HTML_SELECT);
        }
    }

    private String[] getStaticSql(String driverClassName, String url) {
        String[] sql = new String[]{table_mysql, column_mysql};
        if (driverClassName.indexOf("mysql") > -1) {
            return sql;
        } else if (driverClassName.indexOf("oracle") > -1 || url.indexOf("oracle") > -1) {
            sql[0] = table_oracle;
            sql[1] = column_oracle;
        } else if (driverClassName.indexOf("sqlserver") > -1 || url.indexOf("sqlserver") > -1) {
            sql[0] = table_sqlserver;
            sql[1] = column_sqlserver;
        } else if (driverClassName.indexOf("sybase") > -1 || url.indexOf("sybase") > -1) {
            sql[0] = table_sybase;
            sql[1] = column_sybase;
        }

        return sql;
    }

    private GenTable setTableInfo(ResultSet rs) {
        GenTable tableInfo = new GenTable();
        try {
            tableInfo.setTableName(rs.getString("TABLENAME"));
            tableInfo.setTableComment(rs.getString("TABLECOMMENT"));
            tableInfo.setClassName(GenUtil.tableToJava(tableInfo.getTableName(), genProperties.getTablePrefix()));
        } catch (SQLException e) {
            log.error("查询数据库表异常：{}", e.getMessage());
        }
        return tableInfo;
    }

    private List<GenTable> selectTableList(String dbKey, String sql, List<Object> conditions) {
        DataBaseUtil.changeDataSource(dbKey);
        conditions = conditions == null ? Collections.emptyList() : conditions;
        return jdbcTemplate.query(sql, (rs, rowNum) -> setTableInfo(rs), conditions.toArray());
    }

    private List<GenTableColumn> selectColumnList(String dbKey, String tableName, String sql) {
        DynamicDataSourceContextHolder.setDateSourceType(dbKey);
        // 查询数据表
        String temp = sql.replaceAll("\\?table_name", tableName);
        return jdbcTemplate.query(temp, (rs, rowNum) -> setTableColumnInfo(rs));
    }

    private GenTableColumn setTableColumnInfo(ResultSet rs) {
        GenTableColumn genTableColumn = new GenTableColumn();
        try {
            genTableColumn.setColumnName(rs.getString("COLUMNNAME"));
            genTableColumn.setColumnType(rs.getString("DATATYPE"));
            genTableColumn.setColumnComment(rs.getString("COLUMNCOMMENT"));
            String columnKey = rs.getString("COLUMNKEY");
            if ("PRI".equals(columnKey) || "1".equals(columnKey)) {
                genTableColumn.setIsPk(StatusType.NORMAL.getCode());
            } else {
                genTableColumn.setIsPk(StatusType.DELETE.getCode());
            }
        } catch (SQLException e) {
            log.error("查询数据表字段异常：{}", e.getMessage());
        }
        return genTableColumn;
    }

    public List genDBInfo(TbSysDb tbSysDb, String tableName) {
        List result = new ArrayList();
        try {
            List<GenTable> tables;
            Map<String, List<GenTableColumn>> columns = new HashMap<>();
            String sql_column = null;
            String[] initSql = getStaticSql(tbSysDb.getDriverClassName(), tbSysDb.getUrl());
            String temp = initSql[0];
            if (StringUtil.isNotEmpty(tableName)) {
                temp += " and t.table_name='" + tableName + "' ";
            }
            tables = selectTableList(tbSysDb.getDbKey(), temp, null);
            sql_column = initSql[1];
            String sql = sql_column;

            ThreadPoolExecutor executor = taskExecutor.getThreadPoolExecutor();
            List<CompletableFuture<Boolean>> futures = tables.stream().map(genTable ->
                CompletableFuture.supplyAsync(() -> {
                    try {
                        List<GenTableColumn> columnsTemp = selectColumnList(tbSysDb.getDbKey(), genTable.getTableName(), sql);
                        columns.put(genTable.getTableName(), columnsTemp);
                        return true;
                    } catch (Exception e) {
                        return false;
                    }
                }, executor)).collect(Collectors.toList());

            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            result.add(tables);
            result.add(columns);
        } catch (Exception e) {
            log.error("获取数据库数据表信息异常：{}", e.getMessage());
            result.add(0, new ArrayList<GenTable>());
            result.add(1, new HashMap<String, List<GenTableColumn>>());
        } finally {
            DataBaseUtil.clearDataSource();
        }
        return result;
    }

    /**
     * 批量生成代码
     *
     * @param tableIds        表主键数组
     * @param generatorType   生成文件类别：java、html、vue
     */
    public byte[] generatorCode(Long[] tableIds, String generatorType) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        GenTable table;
        for (Long tableId : tableIds) {
            // 查询表信息
            table = genTableService.findById(tableId);
            if (null != table) {
                List<GenTableColumn> columns = genTableColumnService.findByTableId(tableId);
                table.setColumns(columns);
                // 生成代码
                Map<String, String> codes = generatorCode(table, generatorType);
                // 构建zip包
                codes.entrySet().stream().forEach(entry -> {
                    try {
                        // 添加到zip
                        zip.putNextEntry(new ZipEntry(entry.getKey()));
                        IOUtils.write(entry.getValue(), zip, VelocityInitializer.UTF8);
                        zip.closeEntry();
                    } catch (IOException e) {
                        log.error("渲染模板失败，package {}：{}", entry.getKey(), e);
                    }
                });
            }
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 生成代码
     */
    public Map<String, String> generatorCode(GenTable table, String type) {
        // 初始化vm
        VelocityInitializer.initVelocity();

        // 获取模板信息
        VelocityContext context = GenUtil.getVelocityContext(table);

        // 获取模板列表
        List<String> templates = GenUtil.getTemplates(table.getTplCategory());
        // 封装路径
        final Map<String, String> result = Maps.newLinkedHashMapWithExpectedSize(templates.size());
        String path = "", content = "";
        for (String template : templates) {
            if (StringUtil.isNotEmpty(type) && template.indexOf("." + type + ".") == -1) {
                continue;
            }
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, VelocityInitializer.UTF8);
            tpl.merge(context, sw);
            // 文件路径
            String packageName = StringUtil.isEmpty(table.getPackageName()) ? genProperties.getPackageName() : table.getPackageName();
            path = GenUtil.getFileName(template, table.getClassName(), packageName, table.getModuleName());
            content = sw.toString();
            result.put(path, content);
            IOUtils.closeQuietly(sw);
        }

        return result;
    }

    /**
     * 加载bootstrapValidator校验规则
     *
     * @param tableName   数据表名
     * @param type         元数据类别 [1:查询条件 2:表单数据]
     */
    public Map<String, Object> getValidatorFields(String tableName, String type) {
        return getValidatorFields(tableName, type, false);
    }

    /**
     * 加载bootstrapValidator校验规则
     *
     * @param tableName   数据表名
     * @param type        元数据类别 [1:查询条件 2:表单数据]
     */
    public Map<String, Object> getValidatorFields(String tableName, String type, boolean isVue) {
        // 字段层map
        Map<String, Object> field_map = new HashMap<>();
        HashMap<String, Object> params = new HashMap<>();
        params.put("Q_tableName_S_EQ", tableName);
        switch (type) {
            case "1":
                params.put("Q_isQuery_S_EQ", StatusType.NORMAL.getCode());
                break;
            case "2":
                params.put("Q_isEdit_S_EQ", StatusType.NORMAL.getCode());
                break;
        }
        List<Order> orders = new ArrayList<>();
        orders.add(new Order("sort", SqlKey.ASC));
        List<GenTableColumn> columns = genTableColumnService.findByCondition(params, orders);
        if (columns != null && columns.size() > 0) {
            List<Long> columnIds = columns.stream().map(column -> column.getColumnId()).collect(Collectors.toList());
            params.clear();
            params.put("Q_columnId_L_IN", columnIds);
            List<TbSysValidate> list = tbSysValidateService.findByCondition(params);
            if(list != null && list.size() > 0) {
                String columnName, validateName, rules;
                // validator层、验证名称层、验证规则层
                Map<String, Object> validator_map, type_map, rule_map;
                List<Map> validators;
                String[] dic_arr;
                for (TbSysValidate validate : list) {
                    columnName = validate.getColumnName();
                    if(field_map.get(columnName) == null) {
                        validator_map = new HashMap<>();
                        type_map = new HashMap<>();
                        field_map.put(columnName, validator_map);
                    } else {
                        validator_map = (Map<String, Object>) field_map.get(columnName);
                        type_map = (Map<String, Object>) validator_map.get("validators");
                    }
                    validateName = validate.getValidateName();
                    rule_map = new HashMap<>();
                    rules = validate.getRules();
                    rules = StringUtil.isEmpty(rules) ? "{}" : rules;
                    if (isVue) {
                        type_map = generateValidatorForVue(validateName, type_map, rule_map, rules);
                        if (type_map.size() > 0) {
                            validators = (List) field_map.get(columnName);
                            validators.add(type_map);
                            field_map.put(columnName, validators);
                        }
                    } else {
                        dic_arr = rules.split(FrameWorkConstants.SPLIT_PARAM);
                        String tmp_name;
                        String tmp_value;
                        for (int i = 0; i < dic_arr.length; i++) {
                            if(dic_arr[i].indexOf(FrameWorkConstants.SEPARATOR_KEY_VALUE) > -1) {
                                tmp_name = dic_arr[i].split(FrameWorkConstants.SEPARATOR_KEY_VALUE)[0];
                                tmp_value =  dic_arr[i].split(FrameWorkConstants.SEPARATOR_KEY_VALUE)[1];
                                if ("message".equals(tmp_name) && tmp_value.startsWith("[[#")) {
                                    tmp_value = StringUtil.extractMessage(tmp_value, "[[#{", "}]]");
                                    tmp_value = I18nUtil.message(tmp_value);
                                }
                                rule_map.put(tmp_name, tmp_value);
                                type_map.put(validateName, rule_map);
                            } else {
                                type_map.put(validateName, dic_arr[i]);
                                break;
                            }
                        }
                        if ("remote".equals(validateName)) {
                            if (null == rule_map.get("type")) {
                                rule_map.put("type", "get");
                            }
                            if (null == rule_map.get("data")) {
                                rule_map.put("data", "");
                            }
                        }
                        validator_map.put("validators", type_map);
                        field_map.put(columnName, validator_map);
                    }
                }
            }
        }
        return field_map;
    }

    private Map<String, Object> generateValidatorForVue(String validateName, Map<String, Object> type_map, Map<String, Object> rule_map, String rules) {
        switch (validateName) {
            case "notEmpty":
                type_map.put("required", true);
                break;
            case "stringLength":
                generateRuleMap(rule_map, rules);
                type_map.put("type", "string");
                if (rule_map.get("min") != null) {
                    type_map.put("min", Convert.toInt(rule_map.get("min"), 1));
                }
                if (rule_map.get("max") != null) {
                    type_map.put("max", Convert.toInt(rule_map.get("max"), 1));
                }
                break;
            case "stringCase":
                generateRuleMap(rule_map, rules);
                type_map.put("type", "string");
                if (rule_map.get("case").equals("upper")) {
                    type_map.put("validator", "validUpperCase");
                } else {
                    type_map.put("validator", "validLowerCase");
                }
                type_map.put("message", rule_map.get("message"));
                break;
            case "emailAddress":
                type_map.put("type", "email");
                break;
            case "date":
                type_map.put("type", "date");
                break;
            case "digits":
                type_map.put("type", "number");
                break;
            case "greaterThan":
                type_map.put("type", "number");
                generateRuleMap(rule_map, rules);
                if (null != rule_map.get("value")) {
                    type_map.put("min", Convert.toInt(rule_map.get("value"), 1));
                }
                break;
            case "lessThan":
                type_map.put("type", "number");
                generateRuleMap(rule_map, rules);
                if (null != rule_map.get("value")) {
                    type_map.put("max", Convert.toInt(rule_map.get("value"), 1));
                }
                break;
            case "identical":
                generateRuleMap(rule_map, rules);
                type_map.put("validator", "validIdentical");
                type_map.put("param", rule_map.get("field"));
                break;
            case "choice":
                generateRuleMap(rule_map, rules);
                type_map.put("type", "array");
                if (null != rule_map.get("min")) {
                    type_map.put("min", Convert.toInt(rule_map.get("min"), 0));
                }
                if (null != rule_map.get("max")) {
                    type_map.put("max", Convert.toInt(rule_map.get("max"), 1));
                }
                break;
            case "different":
                generateRuleMap(rule_map, rules);
                type_map.put("validator", "validDifferent");
                type_map.put("param", rule_map.get("field"));
                break;
            case "regexp":
                type_map.put("validator", "validRegexp");
                break;
            case "uri":
                type_map.put("type", "url");
                break;
            case "remote":
                generateRuleMap(rule_map, rules);
                type_map.put("validator", "validRemote");
                type_map.put("param_url", rule_map.get("url"));
                type_map.put("param_type", Convert.toStr(rule_map.get("type"), "get"));
                type_map.put("param_data", Convert.toStr(rule_map.get("data"), ""));
                break;
        }

        return type_map;
    }

    private void generateRuleMap(Map rule_map, String rules) {
        String[] dic_arr = rules.split(FrameWorkConstants.SPLIT_PARAM);
        String tmp_name;
        String tmp_value;
        for (int i = 0; i < dic_arr.length; i++) {
            if(dic_arr[i].indexOf(FrameWorkConstants.SEPARATOR_KEY_VALUE) > -1) {
                tmp_name = dic_arr[i].split(FrameWorkConstants.SEPARATOR_KEY_VALUE)[0];
                tmp_value =  dic_arr[i].split(FrameWorkConstants.SEPARATOR_KEY_VALUE)[1];
                rule_map.put(tmp_name, tmp_value);
            }
        }
    }
}
